import paramiko
from env import Env


def shell_call_new(host, cmd):
    """
    远程调用，内部使用的是ssh 私钥
    :param cmd:  命令行
    :param host: 调用的主机名
    """
    hostinfo = Env.get_host(host)
    host = hostinfo["host"]
    port = hostinfo["port"]
    username = hostinfo["username"]
    key_path = hostinfo.get("key_path")
    password = hostinfo.get("password")
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if key_path is None:
            ssh.connect(hostname=host, port=port, username=username, password=password)
        else:
            private_key = paramiko.RSAKey.from_private_key_file(key_path)
            ssh.connect(hostname=host, port=port, username=username, pkey=private_key)
        # 执行命令获取 /var/log/secure 文件内容
        stdin, stdout, stderr = ssh.exec_command(cmd)
        # 获取命令结果
        result = stdout.read().decode()
        # 关闭连接
        ssh.close()
        return result
    except paramiko.AuthenticationException:
        print("认证失败，请检查私钥文件或用户名。")
    except paramiko.SSHException as ssh_ex:
        print(f"SSH 连接发生错误: {ssh_ex}")
    except FileNotFoundError:
        print(f"未找到私钥文件: {key_path}")
    except Exception as ex:
        print(f"发生未知错误: {ex}")


pass
